import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { NzNotificationService } from 'ng-zorro-antd';

import { UsermanegeService } from '../../../DM/usermanege.service';
import { AppManageService, App } from '../../../DM/appmanage.service';
import { AuthorizedAppService } from '../../../DM/authorizeapp.service';
@Component({
  selector: 'app-user-app-authorization',
  templateUrl: './user-app-authorization.component.html',
  styleUrls: ['./user-app-authorization.component.css']
})
export class userAppAuthorizationComponent implements OnInit {

  _currentStep: number = 1;
  _appLs: App[] = []; // 全部应用
  _authedAppLs: App[] = []; // 授权应用
  _userId: string; // 用户id
  _isReg: boolean; // 是否由注册页跳转
  _currentPageIndex: number = 1; // 当前页
  _indeterminate: boolean = false; // 没有全选也没有全不选
  _allChecked: boolean = false; // 全选
  _disabledButton: boolean = true; // “更新配置”按钮的状态
  _loadingData: boolean = false; // 加载状态

  constructor(
    private usermanegeService: UsermanegeService,
    private appManageService: AppManageService,
    private authorizedAppService: AuthorizedAppService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private msgService: NzMessageService,
    private noticeService: NzNotificationService,
  ) { }

  async ngOnInit() {
    this._appLs = await this.appManageService.getAppList();
    this._loadingData = false;
    this.activatedRoute.params.subscribe(async (res: { id: string, reg: string }) => {
      this._userId = res.id;
      this._isReg = (res.reg === "true");
      // 已授权app
      this._authedAppLs = await this.authorizedAppService.getAuthorizedApp(this._userId);
      // 所有app
      this._appLs.forEach((app: App) => {
        for (let i = 0, length = this._authedAppLs.length; i < length; i++) {
          if (this._authedAppLs[i].AppId == app.AppId) {
            app.checked = true;
            return;
          } else app.checked = false;
        }
      });
      this.refreshStatus();
      this._disabledButton = true;
    })
  }

  async updateAuthorized(): Promise<void> {
    try {
      this._loadingData = true;
      let appIds = [];
      this._appLs.forEach((app: App) => {
        if (app.checked) appIds.push(app.AppId);
      });
      await this.authorizedAppService.updateAuthorizedApp(this._userId, appIds);
      this.msgService.success('授权成功');
      this.noticeService.blank('app授权', `您刚刚为用户进行了授权操作`);
      await this.ngOnInit();
    } catch (err) {
      console.error(err);
      this.msgService.error('授权失败');
      this.noticeService.blank('app授权', `由于${err}，用户授权操作失败`);
    }
  }

  // 全选
  checkAll(status: boolean) {
    this._appLs.forEach((app: App) => {
      app.checked = status;
    });
    this.refreshStatus();
  }

  // 更新状态
  refreshStatus() {
    this._disabledButton = false;
    const checkedAll = this._appLs.every((app: App) => app.checked === true);
    const unCheckedAll = this._appLs.every((app: App) => app.checked === false);
    this._allChecked = checkedAll;
    this._indeterminate = (!checkedAll) && (!unCheckedAll);
  }

}
